Ext.ns('app.medialib');
/**
 * Media library item edit window
 * @extend {Ext.Window}
 */
Ext.define('app.imageSizeWindow',{
	
	extend:'Ext.Window',
	
	imageRecord:null,
 
	constructor: function(config) {
		config = Ext.apply({
			modal: true,
	        layout:'fit',
	        title: appLang.MODULE_MEDIALIB + ' :: '+ appLang.SELECT_IMAGE_SIZE,
	        width: 300,
	        height: 198,      
	        autoScroll:true,
	        closeAction: 'destroy',
	        resizable:false,
	        bodyPadding:3
	    }, config);		
		
		this.callParent(arguments);
	},
	initComponent : function()
	{	
			var original = Ext.create('Ext.form.field.Radio',{
				name:"size" , 
				boxLabel:appLang.ORIGINAL , 
				value:'on',
				checked:true
			});
			var groupItems = [original];
			
			for (index in  app.imageSize){
				if(typeof i == 'function' || app.imageSize[index] == undefined){
					continue;
				}
				groupItems.push({name:"size" , boxLabel:index +' ('+app.imageSize[index][0]+'x'+app.imageSize[index][1]+')' , inputValue:'-'+index });		
			}

			this.height = groupItems.length*30+40;
			
			var groupFld = Ext.create('Ext.form.RadioGroup',{
				xtype:'radiogroup',
				columns:1,
				width:250,
				items:[groupItems]
			});
			
			this.items = [Ext.create('Ext.form.RadioGroup',{
				xtype:'radiogroup',
				columns:1,
				items:[groupItems]
			})];
					
			this.buttons=[
			     {
			    	 text:'Select',
			    	 listeners:{
			    		 click:{
			    			 fn:function(){
			    				 var value = original.getGroupValue();
			    				 if(value=='on'){
			    					 value = '';
			    				 }
			    				 this.fireEvent('sizeSelected', value);
			    				 this.close();
			    			 },
			    			 scope:this
			    		 }
			    	 }
			     },{
			    	 text:'Cancel',
			    	 listeners:{
			    		 click:{
			    			 fn:function(){
			    				 this.fireEvent('selectCanceled');
			    				 this.close();
			    			 },
			    			 scope:this
			    		 }
			    	 }
			     }   
			 ];
			
			
		 	this.callParent(arguments);
	        this.addEvents(
	            /**
	             * @event sizeSelected
	             * @param string size
	             */
	           'sizeSelected',
	           /**
	            * @event selectCanceled
	            */
	           'selectCanceled'
	       );  
	       
	  }
});

Ext.define('app.medialibFilesModel', {
    extend: 'Ext.data.Model',
    fields: [
              {name:'id',type:'integer'},
	          {name:'type',type:'string'},
	          {name:'url',type:'string'},
	          {name:'thumb',type:'string'},
	          {name:'title'},
	          {name:'size'}
    ]
});
/**
 * Media library file upload  Window
 * @author Kirill Egorov 2011
 * @extend Ext.Window
 */
Ext.define('app.fileUploadWindow',{
	extend:'Ext.Window', 
	
	contentPanel:null,

	constructor: function(config) {
			config = Ext.apply({
				modal: true,
		        layout:'fit',
		        title: appLang.MODULE_MEDIALIB + ' :: '+ appLang.FILE_UPLOAD,
		        width: 420,
		        height: 500,        
		        closeAction: 'destroy',
		        resizable:false,
		        items:[]
		    }, config);		
			
		this.callParent(arguments);
	},
	
	initComponent:function(){
		var accExtString = '<h2>'+appLang.MAX_UPLOAD_FILE_SIZE+'</h2> ' + app.maxFileSize;
		
		for(i in app.mediaConfig) {
			if(Ext.isEmpty(i.title)){
				accExtString+='<h2>' + app.mediaConfig[i].title + '</h2> ';
				var cnt = 0;
				var len = app.mediaConfig[i].extensions.length;
				Ext.each(app.mediaConfig[i].extensions , function(extName){
					if(cnt < (len-1)){
						accExtString+=extName+', ';
					}else{
						accExtString+=extName;
					}
					cnt++;
				});
				accExtString+='<br>';
			}
		}
	
		this.formatsPanel = Ext.create('Ext.Panel',{
				title:appLang.ACCEPTED_FORMATS,
				layout:'fit',
				autoScroll:true,
				padding:5,
				frame:true,
				html:accExtString
		});
		
		
		this.simpleUpload = Ext.create('Ext.form.Panel',{
			  region:'north',
			  fileUpload:true,
			  padding:5,
			  height:80,
			  frame:true,
			  border:false,
			  
			  fieldDefaults:{
				  anchor:"100%",
				  labelWidth:3
			  },
			  items:[{
			  	    	   xtype: 'filefield',
			  	    	   emptyText: appLang.SELECT_FILE,
			  		       buttonText: '',
			  		       buttonCfg: {
			  		           iconCls: 'upload-icon'
			  		       },
			  	    	   name:'file'
			  	       }
			  	],
			  	buttons:[
					{
						text:'Upload',
						listeners:{
							'click':{
								fn:function()
								{
									 this.simpleUploadStart();
									  $('#fupload').uploadifyUpload();
								},
								scope:this
							}
						}
					}
			  	]
		  });
	
		  this.simpleUploadedGrid =  Ext.create('Ext.grid.Panel',{
			  region:'center',
			  store: Ext.create('Ext.data.Store',{
			      autoLoad:false,
				  idProperty:'url',
				  model:'app.medialibFilesModel'
			  }),	
			  viewConfig:{
				  stripeRows:true
			  },
			  frame: false,
		      loadMask:true,
			  columnLines: false,
			  autoScroll:true,
			  columns:[
			           {
			        	  text:appLang.ICON,
			        	  dataIndex:'thumb',
			        	  align:'center',
			        	  xtype:'templatecolumn',
			        	  tpl:new Ext.XTemplate(
	        			   		'<div style="white-space:normal;">',
	        			   			'<img src="{thumb}" alt="[icon]" style="border:1px solid #000000;"/>',
	        			    	'</div>'
			        	   ),
			        	   width:80
			           }, {
			        	   text:appLang.INFO,
			        	   dataIndex:'id',
			        	   flex:1,
			        	   xtype:'templatecolumn',
			        	   tpl: new Ext.XTemplate(
			        			   '<div style="white-space:normal;">',
			        			    '<p>Type: {type}</p>',
			        			    '<p>Title: {title}</p>',
			        			    '<p>Size: {size}</p>',
			        			    '</div>'
			        	   )
			           },{
			        	   xtype:'actioncolumn',
			        	   width:40,
			        	   items:[
			        	          {
			        	        	  icon:'/i/system/document-edit.png',
			        	        	  tooltip:appLang.EDIT_RESOURCE,
			        	        	  handler:function(grid, rowIndex, colIndex){
			        	        		   var win = Ext.create('app.editMediaItemWindow',{
			        	        			  'itemId':grid.getStore().getAt(rowIndex).get('id')
			        	        		   });
			        	        			win.on('dataSaved',function(){
			        	        				grid.getStore().removeAt(rowIndex);
			        	    					win.close();
			        	    				},this);
			        	        		   win.show();
			        	        	  }
			        	          }
			        	   ]
			           }
			   ]
		  });
	
		
		  this.multiUpload = Ext.create('Ext.Panel',{
			  title:appLang.MULTIPLE_FILE_UPLOAD,
			  frame:true,
			  autoScroll:true,
			  html:'<div id="fileUpload">'+appLang.MSG_JS_PROBLEM+'</div>',
			  buttons:[{
					text:appLang.CLEAR,
					listeners:{
						'click':{
							fn:function(){
								try{
									$('#fileUpload').uploadifyClearQueue();
								}catch(e){
									
								}
							},
							scope:this
						}
					}
				},
				{
					text:appLang.UPLOAD,
					listeners:{
						'click':{
							fn:function()
							{
								try{
									$('#fileUpload').uploadifyUpload();
								  }catch(e){
										
								}
							},
							scope:this
						}
					}
				}
				]
		  });
		  
		  this.simplePanel = Ext.create('Ext.Panel',{
			  title:appLang.SIMPLE_UPLOAD,
			  layout:'border',
			  items:[
			         this.simpleUpload,  this.simpleUploadedGrid
			  ]
		  });
  
		 this.contentPanel = Ext.create('Ext.tab.Panel' , {
			    activeTab: 1,
				frame:true,
				autoScroll:true,
				items:[this.simplePanel ,this.multiUpload ,this.formatsPanel]
			});
		
		this.items=[this.contentPanel];
	
		this.on('show', function(window){

				$("#fileUpload").uploadify({
					'uploader': '/js/lib/uploadify/uploadify.swf',
					'cancelImg': '/js/lib/uploadify/cancel.png',
					'script': app.admin + app.delimeter + 'medialib' +  app.delimeter + 'upload',
					'folder': 'files',
					'multi': true,
					'buttonText': appLang.SELECT_FILES,
				 	//'width': 80,
					'scriptData':{'sid' : app.getCookie(app.sid),'action':'upload','uploadify':1},
					'rollover': false,
				 	'simUploadLimit':1,
				    'queueSizeLimit':100,
				 	'removeCompleted':false
				});
				//this.doLayout();
			} , this);
		
		this.callParent(arguments);
	},
	
	/**
	 * Simple upload form submit
	 */
	simpleUploadStart:function(){
	    var handle = this;
		this.simpleUpload.getForm().submit({
			    clientValidation: true,
        		url: app.admin + app.delimeter + 'medialib' +  app.delimeter + 'upload',
                waitMsg: appLang.UPLOADING,
                success: function(form, responce)
                {
                	var dat = responce.result.data ;     
                	
                	 Ext.each(dat,function(item){            		 
                		 var rec = new app.medialibFilesModel({
	                             'id':item.id,
	                             'type':item.type,
	                             'url': item.url,
	                             'thumb': item.thumb,
	                             'name':false,
	                             'title':item.title,
	                             'size':item.size
                         });
                		 handle.simpleUploadedGrid.getStore().insert(0, rec);          		 
                	 });
                	 handle.simpleUpload.getForm().reset();
                },
            	failure: app.formFailure
            });     
         }
});

Ext.define('app.medialibModel', {
    extend: 'Ext.data.Model',
    fields: [
            {name:'id' , type:'integer'},
 	        {name:'thumb' , type:'string'},
 	        {name:'date', type:"date", dateFormat: "Y-m-d H:i:s"},		
 	        {name:'modified',type:'string'},
 	        {name:'title',type:'string'},
 	        {name:'alttext',type:'string'},  
 	        {name:'icon',type:'string'},  
 	        {name:'small',type:'string'},  
 	        {name:'mini',type:'string'},  
 	        {name:'thumbnail',type:'string'},  
 	        {name:'medium',type:'string'},  
 	        {name:'large',type:'string'},  
 	        {name:'text',type:'string'},	
 	        {name:'caption',type:'string'}, 	
 	        {name:'description',type:'string'}, 	
 	        {name:'size',type:'float'}, 	
 	        {name:'user_id',type:'integer'}, 
 	        {name:'path',type:'string'},
 	        {name:'type',type:'string'},
 	        {name:'user_name',type:'string'},
 	        {name:'ext',type:'string'}
    ]
});

/**
 * Media library panel component
 * @author Kirill Egorov 2011
 * @extend Ext.Panel
 */
Ext.define('app.medialibPanel',{
		extend:'Ext.Panel',
	   /**
	    * @var {Ext.grid.GridPanel}
	    */
	   dataGrid:null,
	   /**
	    * @var {Ext.data.JsonStore}
	    */
	   dataStore:null,
	   /**
	    * @var {Ext.form.FormPanel}
	    */
	   dataPropertiesForm:null,
	   /**
	    * @var {Ext.Panel}
	    */
	   dataProperties:null,
	     
	   searchField:null,
	   
	   showType:'select',
	   
	   srcTypeFilter:null,
	   
	   constructor: function(config) {	
			config = Ext.apply({
				layout:'border',
				tbar: new Ext.Panel({
					border:false,
					bodyBorder:false,
					items:[]
				})
		    }, config);		
			
			this.callParent(arguments);
	   },
	   initComponent:function(){
			
			this.dataStore = Ext.create('Ext.data.Store', {
			    model: 'app.medialibModel',
			    proxy: {
			        type: 'ajax',
			        url: app.admin + app.delimeter + 'medialib' +  app.delimeter + 'list',				 	
			        reader: {
			            type: 'json',
			            root: 'data',
			            totalProperty: 'count',
			            idProperty: 'id'
			        },
			        startParam:'pager[start]',
			        limitParam:'pager[limit]',
			        sortParam:'pager[sort]',
			        directionParam:'pager[dir]'
			    },
			    pageSize: 30,
		        remoteSort: true,
			    simpleSortMode: true,
			    autoLoad: true,
			    sorters: [{
	                  property : 'date',
	                  direction: 'DESC'
	            }]
			});

			var handle = this;
			
			var columnConfig = [];
			
			if(this.canEdit){
				columnConfig.push(
						{
			            	xtype:'actioncolumn',
			            	align:'center',
			            	width:30,
			            	items:[
			            	       {
			            	    	   tooltip:appLang.EDIT_RECORD,
			            	    	   icon:'/i/system/edit.png',
			            	    	   width:30,
			            	    	   iconCls:'buttonIcon',
			            	    	   handler:function(grid, rowIndex, colIndex){
			            	    		   handle.showEdit(grid.getStore().getAt(rowIndex));
			            	    	   }
			            	       }
			            	]
			            }
				);
			}
			
			columnConfig.push({
					        	 text:appLang.ICON,
					        	 dataIndex:'id',
					        	 width:80,
					        	 align:'center',
					        	 sortable:false,
					        	 xtype:'templatecolumn',
					        	 tpl: new Ext.XTemplate(
					        			   '<div style="white-space:normal;" >',
					        			   		'<img src="{icon}?{modified}" alt="[icon]"  style="border:1px solid #000000;"/>',
					        			   '<div>'
					        	   ) 
					         });
						         
						         
			columnConfig.push({			        	 
					        	 text:appLang.TITLE,
							    // id:'title',
							     dataIndex:'title',
					        	 sortable:true,
					        	 xtype:'templatecolumn',
					        	 flex:1,
					        	 tpl: new Ext.XTemplate(
					        			   '<div style="white-space:normal;" >',
					        			   		'<p><b>Title:</b> {title}</p>',
					        			   		'<p><b>Type:</b> {type}</p>',
					        			   		'<p><b>Size:</b> {size} mb</p>',
					        			   		'<p><b>Uploaded by:</b> {user_name} </p>',
					        			   		'<p><b>Caption:</b> {caption} </p>',
					        			   '<div>'
					        	   ) 
						     });
			
		  columnConfig.push({
						    	 text:appLang.UPLOAD_DATE,
					        	 width:110,
					        	 dataIndex:'date',
					        	 xtype:'datecolumn',
					        	 sortable:true,
					         	 format:'M d, Y H:i'
					         }
					);
			
			if(this.showType == 'main' && this.canDelete){
				columnConfig.push({
						xtype:'actioncolumn',
						width:20,
						align:'center',
						items:[
						       {
						    	   icon:'/i/system/delete.gif',
						    	   tooltip:appLang.DELETE,
						    	   scope:this,
						    	   handler:function(grid, rowIndex, colIndex){
						    		   this.deleteItem(grid.getStore().getAt(rowIndex));					    		
						    	   }
						       }
						 ]
				});
			}
			
			
			this.dataGrid = Ext.create('Ext.grid.Panel',{
				store:this.dataStore,
				region:'center',
				viewConfig:{
					stripeRows:true 
				},
				frame: false,
		        loadMask:true,
				columnLines: false,
				autoScroll:true,
				columns:columnConfig,
				bbar: Ext.create('Ext.PagingToolbar', {
		            store: this.dataStore,
		            displayInfo: true,
		            displayMsg: appLang.DISPLAYING_RECORDS+' {0} - {1} '+appLang.OF+' {2}',
		            emptyMsg:appLang.NO_RECORDS_TO_DISPLAY
		        })
			});
			
			
			this.dataPropertiesForm = Ext.create('Ext.form.Panel',{
					hidden:true,
					frame:true,
					border:false,
					autoScroll:true,
					
					fieldDefaults:{						
						labelAlign:'left',
						labelWidth:120,
						bodyStyle:'font-size:12px;',
						labelStyle: 'font-weight:bold;',
						xtype:'displayfield',
						anchor:"100%"
					},
					defaultType: 'displayfield',
					items: [
					    {
							xtype:'imagefield',
							fieldLabel:appLang.THUMBNAIL,
							name:'thumbnail'
						},{
							allowBlank: false,
							fieldLabel:appLang.TYPE,
							name:"type"
						},{
							allowBlank: false,
							fieldLabel:appLang.TITLE,
							name:"title"
						},{
							allowBlank: false,
							fieldLabel:appLang.SIZE_MB,
							name:"size"
						},{
							allowBlank: false,
							fieldLabel:appLang.UPLOADED_BY,
							name:"user_name"
						},{
							fieldLabel:appLang.ALTER_TEXT,
							name:"alttext"
						},{
							fieldLabel:appLang.CAPTION,
							name:"caption"
						},{
							fieldLabel:appLang.DESCRIPTION,
							name:"description"
						}]		
						
			});
			
			this.dataProperties = Ext.create('Ext.Panel',{
					region:'east',
					layout:'fit',
					width:350,
					minWidth:350,
					autoScroll:false,
					split:true,
					frame:true,
					border:false,
					items:[this.dataPropertiesForm]
			});
			
		
			this.srcTypeFilter = Ext.create('Ext.form.ComboBox',{
					displayField:"text",
					queryMode:"local",
					forceSelection:true,
					store:  Ext.create('Ext.data.Store',{ 
							model:'app.comboStringModel',
							data:[
							      {id:"", text:appLang.ALL},
							      {id:"file", text:appLang.FILE},
							      {id:"image", text:appLang.IMAGE},
							      {id:"audio", text:appLang.AUDIO},
							      {id:"video", text:appLang.VIDEO}
							]
					}),
					triggerAction:"all",
					valueField:"id",
					allowBlank: false,
					value :"",
					width: 150
			});
			
			this.srcTypeFilter.on('select' , function(field, value, options){
				 	this.dataStore.proxy.extraParams['filter[type]'] = field.getValue();
				 	this.dataStore.load();
			 },this);
		 
			 this.searchField = new SearchPanel({
				 store:this.dataStore,
				 local:false
			 });
			  
			this.tbar=[				
				  {
					text:appLang.ADD_FILES,
					hidden:!this.canEdit,
					listeners:{
						click:{
								fn:function(){
					  					var win =  Ext.create('app.fileUploadWindow',{});
					  					win.show();
								},
								scope:this
						}
					}
				},	
	       		this.searchField,
	       		'-',
	       		appLang.MEDIA_TYPE_FILTER+':',
	       		this.srcTypeFilter					
			];
			
			this.dataGrid.getSelectionModel().on('select',function(sm,record,rowIndex,options){
					this.dataPropertiesForm.getForm().reset();
					this.dataPropertiesForm.getForm().loadRecord(record);
					this.dataPropertiesForm.getForm().findField('thumbnail').setValue(record.get('thumbnail')+'?'+record.get('modified'));
					this.dataPropertiesForm.show();		
			},this);
			
			this.dataGrid.getSelectionModel().on('deselect',function(){
				this.dataPropertiesForm.hide();
			},this);
			
			
			if(this.canEdit){			
				this.dataGrid.on('itemdblclick',function(view , record , number , event , options){
					this.showEdit(record);
				},this);
			}

			this.items = [this.dataGrid , this.dataProperties];	
			this.callParent(arguments);
		},
		showEdit:function(record){
			
			var win = Ext.create('app.medialib.EditWindow' , {
				mainGridId:this.dataGrid.getId(),
				viewFormId:this.dataPropertiesForm.getId(),
				recordId:record.get('id'),
				dataRec:record
			});

			win.on('dataSaved',function(){
				this.dataGrid.getSelectionModel().clearSelections();
				this.dataStore.load();				
				win.close();
			},this);
				
			win.show();		
		},
		deleteItem: function(record){
			var handler = this;
			Ext.Ajax.request({
					url: app.admin + app.delimeter + 'medialib' +  app.delimeter + 'remove',
		    		method: 'post',	
		    		timeout:240000,
		    		params: {
		    			'id':record.get('id')
		    		},
		    		success: function(response, request) {
		    			response =  Ext.JSON.decode(response.responseText);
		    			if(response.success){
		    				handler.dataStore.remove(record);
		    			}else{
		    			    Ext.Msg.alert(appLang.MESSAGE, response.msg); 	
		    			}
		    	  },
		          failure:function() {
		          	Ext.Msg.alert(appLang.MESSAGE, appLang.CANT_EXEC);   	
		          }
		    	});
		}
});

Ext.define('app.selectMediaItemWindow',{
	extend:'Ext.Window',
	/**
	 * @var {app.medialibPanel }
	 */
	medialibPanel:null,
	actionType:'selectId',
	resourceType:'all',
	
	constructor: function(config) {
		config = Ext.apply({
			modal: true,
	        layout:'fit',
	        title: appLang.MODULE_MEDIALIB + ' :: '+ appLang.EDIT_ITEM,
	        width: 750,
	        height: app.checkHeight(600),     
	        closeAction: 'destroy',
	        resizable:true,
	        items:[],
	        tools:app.windowToolsElements()
	    }, config);		
		this.callParent(arguments);
	},
	selectItem:function()
	{

		switch(this.actionType){
			case 'selectId' :
				var sm = this.medialibPanel.dataGrid.getSelectionModel();
				
				if(!sm.hasSelection()){
					Ext.MessageBox.alert(appLang.MESSAGE,appLang.MSG_SELECT_RESOURCE);
					return;
				}
				
				var rec = sm.getSelection()[0];
		
				if(this.resourceType!='all' && this.resourceType != rec.get('type')){	
					Ext.MessageBox.alert(appLang.MESSAGE,appLang.SELECT_PLEASE+' '+this.resourceType + ' '+ appLang.RESOURCE);
					return;
				}
				
				this.fireEvent('itemSelected', rec);
				/*
				var me = this;
				me.getEl().mask('Item selected');
				setTimeout(function(){
					me.getEl().unmask();
				},500);
				*/
				break;
		}
	},
    initComponent : function(){
		
		this.medialibPanel = Ext.create('app.medialibPanel',{
			 actionType:this.actionType,
			 border:false
		});
		this.items=[this.medialibPanel];
		
		if(this.resourceType !='all'){
			this.medialibPanel.srcTypeFilter.setValue(this.resourceType);
			this.medialibPanel.srcTypeFilter.disable();
			this.medialibPanel.dataStore.proxy.extraParams['filter[type]']=this.resourceType;
			this.medialibPanel.dataStore.load();
		}

		var me = this;
		
		this.buttons=[
		           {
		        	    text:appLang.SELECT,
		        	    scope:me,
		        	    handler:me.selectItem 
		           },{
		        	   text:appLang.CLOSE,
		        	   scope:me,
		        	   handler:me.close 
		           }
		];
		
		this.callParent(arguments);
        this.addEvents(
            /**
             * @event itemSelected
             * @param {Ext.data.Record} record
             */
            'itemSelected'
        );
	}
});
